/*
 * author M.Chang
 *
 * Copyright 2008 Ph.Bonnet and M.Chang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

#include "MinizincPlanner.h"



/*****************************************************************************/

/* constructor */
MinizincPlanner::MinizincPlanner()
{
}


/* destructor */
MinizincPlanner::~MinizincPlanner()
{
}


/*****************************************************************************/

bool MinizincPlanner::solve(const std::string& minizinc_string, std::vector<std::string>& optimal_solution_vector)
{

  /* write minizinc file */
  std::ofstream outfile("dummy.mzn", std::ios_base::out | std::ios_base::trunc);

  if (outfile.is_open()){
    outfile << minizinc_string;
    outfile.close();
  }
  else
    std::cout << "Unable to open file" << std::endl;

  /* parse minizinc file to flatzinc and solve */
  std::stringstream cmd_stream;

  cmd_stream << minizinc_to_flatzinc << " " << temporary_flatzinc_file << ".mzn;";
  cmd_stream << flatzinc_solver << " " << temporary_flatzinc_file << ".fzn > " << temporary_output_file;

  system(cmd_stream.str().c_str());

  /***************************************************************************/
  std::string buffer_string, output_string;
  std::ifstream output_file(temporary_output_file);
  if (output_file.is_open())
  {
    while (!output_file.eof())
    {
      std::getline(output_file, buffer_string);
      output_string.append(buffer_string);
      output_string.append("\n");
    }
    output_file.close();
  }else
    std::cout << "Unable to open file";


//  std::cout << output_string << std::endl;

  /***************************************************************************/

  std::vector<std::string> solutions_vector;

  Tokenize::Tokens(output_string, solutions_vector, "<begin>", "<end>");

  if (solutions_vector.empty())
  {
    std::cout << "No solution found." << std::endl;
    return false;
  }

  Tokenize::Tokens(solutions_vector.back(), optimal_solution_vector, "\n");

  if (optimal_solution_vector.empty())
    return false;

  return true;
}








